package com.ty.springbootshiro.controller;

import com.ty.springbootshiro.config.MyShiroRealm;
import com.ty.springbootshiro.entity.Right;
import com.ty.springbootshiro.entity.Role;
import com.ty.springbootshiro.entity.User;
import com.ty.springbootshiro.service.RoleService;
import com.ty.springbootshiro.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * IndexConfig
 *
 * @aurhor Administrator  whs
 * @since 2024/9/13
 */
@Controller
public class IndexController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // Redis 中数据的key前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_"; // 登录计数

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    /**
     * 去登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    @RequestMapping("/403")
    public String unauthorized() {
        return "403";
    }

    @RequestMapping("/login")
    public String login(String usrName, String usrPassword, Model model, HttpSession session) {
//        User loginUser = userService.login(usrName, usrPassword);
//        if (loginUser != null) {
//            session.setAttribute("loginUser", loginUser);
//            return "redirect:/main";
//        }else {
//            model.addAttribute("meg","账号或密码错误");
//            return "login";
//        }

        try {

            // 加密处理
//            usrPassword = userService.encryptPassword(usrPassword);

//            System.out.println("usrPassword-------------------> " + usrPassword);

            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token); // 认证登录

            // 如果认证（登录）成功，清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);

            User user = (User) subject.getPrincipal();
            System.out.println("user ------ > " + user);
            session.setAttribute("loginUser", user);

//            获取权限
            Role role = user.getRole();
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            model.addAttribute("rights", rights);
            session.setAttribute("loginUser", user);

            // 清空权限缓存
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());

            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        }catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        }catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout(); // shiro 注销
        return "redirect:/login";  //重定向 保证删除Cookie
    }
}
